
<%@ page contentType="text/html; charset=utf-8" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" 
%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>jqgrid.jsp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="${pageContext.request.contextPath}/js/jquery/jquery-1.11.0.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/js/jquery/ui/css/redmond/jquery-ui-1.10.4.custom.css" />
<script src="${pageContext.request.contextPath}/js/jquery/ui/js/jquery-ui-1.10.4.custom.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/vendor/jquery.ui.widget.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/jquery.iframe-transport.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/jquery.fileupload.js" type="text/javascript"></script>
<c:set value="${pageContext.request.contextPath}/app/sample.uploadfile/message" var="messageUploadUrl"/>
<c:set value="${pageContext.request.contextPath}/app/sample.uploadfile/file.tx" var="fileUploadUrl"/>
<script type="text/javascript">
$(function() {
	init();
});

function init() {
	$('input:button').button();
	$('#submit').button();
	
	$('#uploadForm').submit(function(event) {
		event.preventDefault();	
		
// 		$.postJSON('${messageUploadUrl}', {
// 					owner: $('#owner').val(),
// 					description: $('#description').val(),
// 					filename: getFilelist()
// 				},
// 				function(result) {
// 					if (result.success == true) {
// 						dialog('Success', 'Files have been uploaded!');
// 					} else {
// 						dialog('Failure', 'Unable to upload files!');
// 					}
// 		});
		
	    $.ajax({
	    	type: "post",
	    	url: "${messageUploadUrl}",
	    	async: true,
	    	contentType: "application/json;charset=utf-8",
	        data: JSON.stringify({
	        		owner: $('#owner').val(),
					description: $('#description').val(),
					filename: getFilelist()
	        }),
	        dataType: "json",
	    	success: function(data, text, request) {
	    		console.debug(data);
	    	},
	    	error: function(jqXHR, textStatus, errorThrown) {
	    		alert("처리 중 오류가 발생하였습니다.");
	    	}
	    });	
	});
	
	$('#reset').click(function() {
		clearForm();
		dialog('Success', 'Fields have been cleared!');
	});
	
	$('#upload').fileupload({
		// File API를 지원하는 IE10+, Chrome 등 지원  
		add: function(e, data) {
			var isOK = true;
			
			if (data.files.length > 0) {
				var size = data.files[0].size;
				isOK = (!size || size <= 5000000);
			}
			
			if (isOK) { 
				data.submit(); 
			} else {
				alert("파일크기가 초과되었습니다.");
			}
		},
// 		dataType: 'json',
  		dataType: 'text',
        done: function (e, data) {
            $.each(data.result, function (index, file) {
                $('body').data('filelist').push(file);
                $('#filename').append(formatFileDisplay(file));
                $('#attach').empty().append('Add another file');
            });
        },
        fail: function(e, data) {
        	if (data.jqXHR.responseJSON) {
        	    alert(data.jqXHR.responseJSON.message);	
        	} else {
        	    alert("처리 중 오류가 발생하였습니다.");
        	}
        }
    });
    
	// Technique borrowed from http://stackoverflow.com/questions/1944267/how-to-change-the-button-text-of-input-type-file
	// http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input
	$("#attach").click(function () {
	    $("#upload").trigger('click');
	});
	
	$('body').data('filelist', new Array());
}

function formatFileDisplay(file) {
	var size = '<span style="font-style:italic">'+(file.size/1000).toFixed(2)+'K</span>';
	return file.name + ' ('+ size +')<br/>';
}

function getFilelist() {
	var files = $('body').data('filelist');
	var filenames = '';
	for (var i=0; i<files.length; i<i++) {
		var suffix = (i==files.length-1) ? '' : ',';
		filenames += files[i].name + suffix;
	}
	return filenames;
}

function dialog(title, text) {
	$('#msgbox').text(text);
	$('#msgbox').dialog( 
			{	title: title,
				modal: true,
				buttons: {"Ok": function()  {
					$(this).dialog("close");} 
				}
			});
}

function clearForm() {
	$('#owner').val('');
	$('#description').val('');
	$('#filename').empty();
	$('#attach').empty().append('Add a file');
	$('body').data('filelist', new Array());
}
</script>
</head>
<body>
	<h1 id='banner'>Upload Files</h1>
	<div>
		<form id='uploadForm'>
  			<fieldset>
				<legend>Files</legend>
				<label for='owner'>Owner:</label><input type='text' id='owner'/><br/>
				<textarea name="description" id="description">Description here</textarea><br/>
				<span id='filename'></span><br/>
				<a href='#' id='attach'>Add a file</a><br/>
				<input id="upload" type="file" name="file" data-url="${fileUploadUrl}" multiple style="opacity: 0; filter:alpha(opacity: 0);"><br/>
				<input type='button' value='Reset' id='reset' />
				<input type='submit' value='Upload' id='submit'/>
  			</fieldset>
		</form>
	</div>
	<div id='msgbox' title='' style='display:none'></div>
</body>
</html>